<script setup lang="ts">
  import { ref,watch } from 'vue'
   const emits = defineEmits(['update:modelValue'])
   const props = defineProps({
     unit:String,
     modelValue:{
       type:[String,Number],
       required:true
     },
     negative:{
       type:Boolean
     },
     digit:{
       type:String,
       default:true
     },
     step: {
       type: Number,
       default: 0.01
     },
   })
   const inputValue = ref(props.modelValue)
   const addNumber = () => {
      if(isNaN(Number(inputValue.value))){
        inputValue.value = 0
      }
     inputValue.value = Number(inputValue.value) + 1
     emits('update:modelValue', inputValue.value)
   }
   const delNumber = () => {
    if(inputValue.value == 0 && props.negative) {
      return false
    }
     if(isNaN(Number(inputValue.value))){
       inputValue.value = 0
     }
     inputValue.value = Number(inputValue.value) - 1
     emits('update:modelValue', inputValue.value)
   }
   const inputBlur = (e:any) => {
     let value = e.detail.value;
     if (isNaN(value)) {
       inputValue.value = 0;
       return;
     }
     value = +value;
     const scale = _getDecimalScale();
     inputValue.value = value.toFixed(String(scale).length - 1);
     emits('update:modelValue', +inputValue.value)
   }
   const _getDecimalScale = () => {
     let scale = 1;
     if (~~props.step !== props.step) {
       scale = Math.pow(10, String(props.step).split(".")[1].length);
     }
     return scale;
   }

  watch(() => props.modelValue,(newVal) => {
    let value = +newVal;
    const scale = _getDecimalScale();
    inputValue.value = value.toFixed(String(scale).length - 1);
  })
</script>

<template>
  <view class="input-number">
    <view class="input-number-add" @click="delNumber">-</view>
    <view class="input-number-value">
      <input :type="props.digit?'digit':'number'" class="number-value" @blur="inputBlur" v-model="inputValue"/>
      <view class="unit" v-if="props.unit">{{props.unit}}</view>
    </view>
    <view class="input-number-del" @click="addNumber">+</view>
  </view>
</template>

<style scoped lang="scss">
  .input-number{
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 100rpx;
    background: #F8F8F8;
    height: 60rpx;
    .input-number-add,.input-number-del{
      font-size: 40rpx;
      width: 100rpx;
      line-height: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 100rpx;
      background: #F3F3F3;
      color: #333333;
    }
    .input-number-value{
      display: flex;
      justify-content: space-between;
      align-items: center;
      .number-value{
        text-align: center;
        flex: 1;
      }
      .unit{
        color: #21252E;
      }
    }
  }
</style>
